package xyz.mumuwei.youthcourseserver.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import xyz.mumuwei.youthcourseserver.common.dto.PageDto;
import xyz.mumuwei.youthcourseserver.common.lang.Result;
import xyz.mumuwei.youthcourseserver.pojo.Authority;
import xyz.mumuwei.youthcourseserver.service.AuthorityService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author mumuwei
 * @since 2022-02-19
 */
@RestController
@RequestMapping("/authority")
public class AuthorityController {

    private AuthorityService authorityService;

    @Autowired
    public void setAuthorityService(AuthorityService authorityService) {
        this.authorityService = authorityService;
    }

    /**
     * 获取权限列表-分页
     */
    @GetMapping("/page")
    public Result page(PageDto pageDto){
        Page<Authority> rolePage = new Page<>(pageDto.getCurrent(), pageDto.getSize());
        // 获取第一级权限
        IPage<Authority> page = authorityService.page(rolePage, new QueryWrapper<Authority>()
                .like("title", pageDto.getKey())
                .eq("level", 0)
                .orderByDesc("create_time"));
        if(page == null){
            return Result.fail("获取权限列表失败！");
        }
        List<Authority> level0 = page.getRecords();
        List<Authority> level1 = authorityService.list(new QueryWrapper<Authority>().eq("level", 1));
        List<Authority> level2 = authorityService.list(new QueryWrapper<Authority>().eq("level", 2));
        authGrade(level1, level2);
        authGrade(level0, level1);
        return Result.success(page);
    }

    /**
     * 获取权限列表-不分页
     */
    @GetMapping("/list")
    public Result list(){
        List<Authority> leve0 = authorityService.list(new QueryWrapper<Authority>().eq("level", 0).orderByDesc("create_time"));
        List<Authority> leve1 = authorityService.list(new QueryWrapper<Authority>().eq("level", 1).orderByDesc("create_time"));
        List<Authority> leve2 = authorityService.list(new QueryWrapper<Authority>().eq("level", 2).orderByDesc("create_time"));
        if(leve0 == null){
            return Result.fail("获取权限列表失败！");
        }
        authGrade(leve1, leve2);
        authGrade(leve0, leve1);
        return Result.success(leve0);
    }

    /**
     * 根据id获取权限信息
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        Authority authority = authorityService.getById(id);
        if(authority == null){
            return Result.fail("查询失败！");
        }
        // 三级权限直接返回
        if(authority.getLevel() == 2){
            return Result.success(authority);
        }
        // 不论是一级权限 还是二级权限 都要查询三级权限
        List<Authority> level2 = authorityService.list(new QueryWrapper<Authority>()
                .eq("level", 2).orderByDesc("create_time"));
        List<Authority> level0 = new ArrayList<>();
        level0.add(authority);
        if(authority.getLevel()==0){
            // authority 为一级权限
            // 查二级权限
            List<Authority> level1 = authorityService.list(new QueryWrapper<Authority>()
                    .eq("level", 1)
                    .orderByDesc("create_time"));
            // 三级放二级
            authGrade(level1, level2);
            authGrade(level0, level1);
        }else {
            // authority 二级权限，则直接将 leve2三级权限放入
            authGrade(level0, level2);
        }
        authority = level0.get(0);
        return Result.success(authority);
    }

    /**
     * 添加权限
     */
    @PostMapping("")
    public Result create(@Validated Authority authority){
        int level = 0;
        if(authority.getParentId() != 10){
            level = authorityService.getById(authority.getParentId()).getLevel() + 1;
        }
        authority.setLevel(level);
        boolean save = authorityService.save(authority);
        if(save){
            return Result.success("添加权限成功！");
        }
        return Result.fail("添加权限失败！");
    }

    /**
     * 修改权限
     */
    @PostMapping("/update")
    public Result update(@Validated Authority authority){
        boolean update = authorityService.updateById(authority);
        if(update){
            return Result.success("更新权限成功！");
        }
        return Result.fail("更新权限失败！");
    }

    /**
     * 删除权限
     */
    @GetMapping("/d_{id}")
    public Result delete(@PathVariable Integer id){
        boolean b = authorityService.removeById(id);
        if(b){
            return Result.success("删除成功！");
        }
        return Result.fail("删除失败！");
    }

    /**
     * 修改权限状态
     */
    @GetMapping("/s_{id}")
    public Result updateState(@PathVariable Integer id){
        final Authority auth = authorityService.getById(id);
        Authority authority = new Authority();
        authority.setId(id);
        authority.setState(auth.getState()==0 ? 1 : 0);
        boolean update = authorityService.updateById(authority);
        if(update){
            return Result.success("更新状态成功！");
        }
        return Result.fail("更新状态失败！");
    }

    /**
     * 权限分级
     */
    private void authGrade(List<Authority> parent, List<Authority> child){
        for (Authority p : parent){
            List<Authority> children = new ArrayList<>();
            for (Authority c : child){
                if(p.getId().equals(c.getParentId())){
                    children.add(c);
                }
            }
            p.setChildren(children);
        }
    }
}

